package com.powernode.teatraceability.controller.login;


import com.powernode.teatraceability.pojo.login.Account;
import com.powernode.teatraceability.pojo.login.User;
import com.powernode.teatraceability.service.basicinfomgt.EnterpriseService;
import com.powernode.teatraceability.service.user.UserService;
import com.powernode.teatraceability.utils.GlobalConfig;
import com.powernode.teatraceability.utils.JsonData;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
public class LoginController {
    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private UserService userService;

    @PostMapping("/user/login")
    public JsonData login(@RequestBody Account account,
                          HttpSession session){

        JsonData jsonData = new JsonData();
        System.out.println(account);
        if(userService.verify(account.getUsername(), account.getPassword(), account.getGroupName())){
            session.setAttribute("user", GlobalConfig.getUser());
            System.out.println(session.getAttribute("user"));
            System.out.println(session.getId());
            jsonData.setStatus(200);
            jsonData.setMsg("登陆成功");
            User user = (User) session.getAttribute("user");
            user.setQymc(enterpriseService.selectQYMCByQydm(user.getQydm()));
            jsonData.setData(user);
        }else{
            jsonData.setStatus(400);
            jsonData.setMsg("账号或密码有误");
        }
        return jsonData;
    }

    @GetMapping("/user/{act}")
    public JsonData updateInfo(@SessionAttribute(name = "user", required = true) User user,
                               @PathVariable("act") String act) {
        final int i = userService.updateAct(Integer.valueOf(act), user.getRybh());
        if (i > 0) {
            return JsonData.success("更新成功！");
        } else {
            return JsonData.failure(401, "更新失败");
        }
    }
    @GetMapping("/user/info")
    public JsonData userInfo(@SessionAttribute(name = "user", required = true) User user) {
        return JsonData.success(user);
    }

}
